export default class TaskQueue {
    private _taskList = [];
    private _currIndex: number = 0;
    private _isRunnind: boolean;


    addTask(execute: (next: Function, param: any) => any, param: any[]) {
        this._taskList.push({ execute: execute, param: param })
    }

    run() {
        if (this._isRunnind) {
            return;
        }

        this._isRunnind = true;

        this.runTask();
    }

    private async runTask() {
        if (this._currIndex && this._currIndex >= this._taskList.length) {
            return void this.reset();
        }

        let index = this._currIndex;
        let task = this._taskList[this._currIndex];
        await task.execute(this.nextTask.bind(this), ...task.param);

        index === this._currIndex && this.nextTask();
    }

    private nextTask() {
        this._currIndex++;
        this.runTask();
    }

    private reset() {
        this._currIndex = 0;
        this._taskList = [];
        this._isRunnind = false;
    }
}